package com.ddtj.demo1.controller;

import com.ddtj.demo1.component.annotation.Log;
import com.ddtj.demo1.component.utils.OperType;
import com.ddtj.demo1.entity.User;
import com.ddtj.demo1.dao.UserJpa;
import com.ddtj.demo1.pojo.AjaxResult;
import com.ddtj.demo1.service.impl.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserJpa userJpa;
    @Autowired
    UserService userService;
    @GetMapping("/list")
    //@Log(title = OperType.QUERY_OPT)
    public AjaxResult list(){
        List<User> all = userJpa.findAll();
        return AjaxResult.success(all);
    }
    @PostMapping("/save")
    @Log(title = OperType.SAVE_OPT)
    public AjaxResult save(@Validated User user){
        boolean exist = userService.isExist(null, user.getUsername());
        if(exist){
            return AjaxResult.conflict("数据已存在");
        }
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String encode = bCryptPasswordEncoder.encode(user.getPassword());
        user.setPassword(encode);
        userJpa.save(user);
        return AjaxResult.success();
    }
    @DeleteMapping("/delete")
    @Log(title = OperType.DELETE_OPT)
    public AjaxResult delete(User user){
        userJpa.delete(user);
        return AjaxResult.success();
    }
    @PutMapping("/update")
    @Log(title = OperType.UPDATE_OPT)
    public AjaxResult update(@Validated User user){
        boolean exist = userService.isExist(user.getId(), user.getUsername());
        if(exist){
            return AjaxResult.conflict("数据已存在");
        }
        userJpa.save(user);
        return AjaxResult.success();
    }
}
